package com.sentiment.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.sentiment.database.bean.Permission;
import com.sentiment.database.bean.Role;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.User_Permissions;

public class MyRealm  extends AuthorizingRealm {

	// 设置realm的名称
	@Override
	public void setName(String name) {
		super.setName("myRealm");
	}
	
//	// 用于认证 未连接数据库
//	@Override
//	protected AuthenticationInfo doGetAuthenticationInfo(
//			AuthenticationToken token) throws AuthenticationException {
//	
//		// token是用户输入的
//		// 第一步从token中取出身份信息
//		String username = (String) token.getPrincipal();
//		
//		// 第二步：根据用户输入的userCode从数据库查询
//		
//
//		// 如果查询不到返回null
//		// 数据库中用户账号是zhangsansan
//		/*
//		 * if(!userCode.equals("zhangsansan")){// return null; }
//		 */
//
//		// 模拟从数据库查询到密码,散列值
//		String passwordMD5 = "f3694f162729b7d0254c6e40260bf15c";
//		// 从数据库获取salt
//		String salt = "qwerty";
//		//上边散列值和盐对应的明文：111111
//		if(false){//帐号锁定 
//			throw new LockedAccountException();  
//		}
//		
//		
//		ActiveUser activeUser = new ActiveUser();
//		activeUser.setUsername(username);
//		
//
//		// 如果查询到返回认证信息AuthenticationInfo
//		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
//				activeUser, passwordMD5, ByteSource.Util.bytes(salt), this.getName());
//
//		return simpleAuthenticationInfo;
//		
//	
//	}
	
	
	// 用于认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
	
		// token是用户输入的
		// 第一步从token中取出身份信息
		String usercode = (String) token.getPrincipal();
		
		// 第二步：根据用户输入的userCode从数据库查询
		User user = new User();
		user = user.getUserByUserCode(usercode);
		if(user == null)
			return null;
		if(user.isLocked()){//帐号锁定 
			throw new LockedAccountException();  
		}
		//从数据库中取得密码
		String passwordMD5 = user.getPassword();
		// 从数据库获取salt
		String salt = user.getSalt();
		//上边散列值和盐对应的明文：111111
		
		ActiveUser activeUser = new ActiveUser();
		activeUser.setUser_id(user.get_id());
		activeUser.setUsercode(user.getUsercode());
		if(user.getUsername() == null)
			activeUser.setUsername(user.getUsercode());
		else
			activeUser.setUsername(user.getUsername());
		
		// 如果查询到返回认证信息AuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, passwordMD5, ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
		
	}
	

//	// 用于授权未连接数据库
//	@Override
//	protected AuthorizationInfo doGetAuthorizationInfo(
//			PrincipalCollection principals) {
//		
//		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
//		System.out.println("授权数据库查询");
//		List<String> permissions = new ArrayList<>();
//		List<String> roles = new ArrayList<>();
//		
//		permissions.add("/WebPage/jsp/contentComp.jsp");
//		permissions.add("/WebPage/jsp/contentCompTemp.jsp");
//		permissions.add("/WebPage/jsp/correlationInfo.jsp");
//		permissions.add("/WebPage/jsp/dailySentiment.jsp");
//		permissions.add("/WebPage/jsp/dailySentimentReport.jsp");
//		permissions.add("/WebPage/jsp/hotInfoSupervision.jsp");
//		permissions.add("/WebPage/jsp/hotSentiment.jsp");
//		permissions.add("/WebPage/jsp/hotSentimentDetail.jsp");
//		permissions.add("/WebPage/jsp/plagiarismGraph.jsp");
//		permissions.add("/WebPage/jsp/plagiarismList.jsp");
//		permissions.add("/WebPage/jsp/plagiarismText.jsp");
//		permissions.add("/WebPage/jsp/plagiarismUrl.jsp");
//		permissions.add("/WebPage/jsp/sentimentGraph.jsp");
//		permissions.add("/WebPage/jsp/sentimentList.jsp");
//		
//		permissions.add("/WebManagement/dailypublish.jsp");
//		permissions.add("/WebManagement/frame.jsp");
//		permissions.add("/WebManagement/hotpublish.jsp");
//		permissions.add("/WebManagement/index.jsp");
//		permissions.add("/WebManagement/permissionlist.jsp");
//		permissions.add("/WebManagement/rolelist.jsp");
//		permissions.add("/WebManagement/user.jsp");
//		permissions.add("/WebManagement/userlist.jsp");
//		permissions.add("/WebManagement/historyrecord.jsp");
//		permissions.add("/WebManagement/userPaymentsRecord.jsp");
//		permissions.add("/WebManagement/viewUserDetail.jsp");
//		permissions.add("/WebManagement/useredit.jsp");
//		permissions.add("/WebManagement/systemrefer.jsp");
//		permissions.add("/WebManagement/systemedit.jsp");
//		roles.add("admin");
//		
//		activeUser.setPermission(permissions);
//				
//		//查到权限数据，返回授权信息(要包括 上边的permissions)
//		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//		//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
//		simpleAuthorizationInfo.addStringPermissions(permissions);
//		simpleAuthorizationInfo.addRoles(roles);
//
//		return simpleAuthorizationInfo;
//	}
	
	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
		System.out.println("授权数据库查询");
		
		//添加权限
		List<String> permissions = new ArrayList<>();
		List<String> permissions_id = new ArrayList<>();
		Permission per = new Permission();
		User_Permissions user_pers = new User_Permissions();
		user_pers = user_pers.getUser_PermissionsByUser_id(activeUser.getUser_id());
		permissions_id = user_pers.getpermissions_id();
		if(permissions_id == null)
			permissions = null;
		else{
			for(int i = 0; i < permissions_id.size(); i++){
				
				per = per.getPermissionByPermissionId(permissions_id.get(i));
				permissions.add(per.getPermissioncode());
			}
		}

		activeUser.setPermission(permissions);
		
		//添加角色
		User user = new User();
		List<Role> roles = user.getRolesByUser_id(activeUser.getUser_id());
		List<String> rolename = new ArrayList<>();
		if(roles == null)
			rolename = null;
		else{
			for (int i = 0; i < roles.size(); i++) {
		
				rolename.add(roles.get(i).getRolename());
			}
		}
		
		activeUser.setRole(rolename);
		//查到权限数据，返回授权信息(要包括 上边的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
		simpleAuthorizationInfo.addStringPermissions(permissions);
		simpleAuthorizationInfo.addRoles(rolename);

		return simpleAuthorizationInfo;
	}
	
	
	//清除缓存 更改数据库权限后调用该方法清空用户缓存，使用户重新登录,目前未使用
	public void clearCached() {
//		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
//		ActiveUser activeUser = (ActiveUser)principals.getPrimaryPrincipal();
//		super.clearCache(principals);
		
		SecurityUtils.getSubject().logout();
	}
	
}
